<template>
  <a-layout>
    <a-layout-content style="background-color: #F2F2E6">
<!--      解决方案发布成功后显示对话框-->
      <v-dialog v-model="upload_success" width="600" persistent>
        <v-card color="main_1" style="color: snow">
          <v-card-title>
            <v-icon left style="color: snow">mdi-emoticon-happy-outline</v-icon>
            解决方案发布成功，审核通过后将发布到解决方案社区
          </v-card-title>
          <br>
          <v-card-text style="color: snow; padding-left: 2vw; padding-right: 2vw">
            即将前往解决方案仓库
            <v-progress-linear
              indeterminate
              color="white"
              class="mb-0"
            ></v-progress-linear>
          </v-card-text>
        </v-card>
      </v-dialog>
      <br><br><br>
      <!--    步骤条    -->
      <guide-stepper v-if="isShow"/>
<!--      页头-->
      <v-row>
        <v-col cols="12" lg="1">
          <guide-record/>
        </v-col>
        <v-col cols="12" lg="10" style="text-align: center">
          <img src="../../public/images/write.png"
               alt=""
               style="width: 220px; height: 220px; margin-top: 90px"/>
        </v-col>
        <v-col cols="12" lg="1"></v-col>
      </v-row>
      <br><br>
      <p
        align="center"
        style="font-family: '华文楷体',sans-serif; font-size: 35px; color: #89B8CA; font-weight: bolder">
        参考您的专利笔记，在这里创作您的解决方案。
      </p>
<!--      主体-->
      <div
        class="text-right"
        style="padding-top: 5vh"
      >
        <v-row justify-lg="space-between">
          <v-col cols="12" lg="1"></v-col>
          <v-col cols="12" lg="10">
            <v-card style="background-color: #FFFAF4; height: 109vh" elevation="15">
              <v-container fluid>
<!--                标题输入框-->
                <v-text-field
                  ref="head"
                  outlined
                  v-model="draft.name"
                  :rules="header_rules"
                  placeholder="请输入标题（5~20个字）"
                  style="font-size: large; font-weight: bolder; text-align: center"
                >
                </v-text-field>
<!--                富文本编辑器-->
                <mavon-editor
                  ref="md"
                  v-model="draft.detail"
                  :ishljs="true"
                  :toolbars="toolbars"
                  placeholder="请在此处编辑..."
                  @imgAdd="imgAdd"
                  @save="save_as_draft"
                  toolbarsBackground="#FFFAF4"
                  style="height: 85vh; z-index: 1 !important;"
                  @change="onEditorChange($event)"
                />
              </v-container>
            </v-card>
          </v-col>
<!--          专利笔记-->
          <v-col cols="12" lg="1">
            <div class="float-lg-right" style="position: sticky; top: 35vh">
              <v-menu
                transition="slide-x-reverse-transition"
                v-model="menu"
                :close-on-content-click="false"
                :close-on-click="false"
                nudge-top="150"
                z-index="1"
              >
<!--                固钉按钮-->
                <template v-slot:activator="{ on, attrs }">
                  <v-btn
                    color="primary"
                    class="ma-2"
                    fab
                    @click="open_note_list"
                    v-show="!menu"
                  >
                    <v-icon>
                      mdi-book-outline
                    </v-icon>
                  </v-btn>
                </template>
<!--                笔记-->
                <v-card
                  width="48vw"
                  elevation="1"
                  class="lg-auto"
                  tile
                >
                  <v-toolbar
                    height="50vh"
                    dark
                    color="#89b8ca"
                    style="z-index: 1501"
                  >
                    <v-toolbar-title>专利笔记</v-toolbar-title>
                    &emsp;
                    <v-btn disabled fab x-small>
                        <span style="color: white; font-size: large">
                          {{note_list.length}}
                        </span>
                    </v-btn>
                    <v-spacer></v-spacer>
                    <v-btn text @click="goto_all_notes">
                      查看所有笔记
                    </v-btn>
                  </v-toolbar>
                  <v-row no-gutters>
<!--                    笔记列表-->
                    <v-col cols="12" lg="3">
                      <v-list
                        nav
                        dense
                        class="overflow-y-auto overflow-x-hidden"
                        height="50vh"
                        color="rgb(246,241,235)"
                      >
                        <v-list-item-group
                          v-model="selectedItem"
                          mandatory
                          color="primary"
                        >
                          <v-list-item
                            v-for="(item, i) in note_list"
                            :key="i"
                            three-line @click="get_detail(item)"
                          >
                            <v-list-item-content>
                              <v-list-item-title>
                                <span>{{item.name}}</span>
                              </v-list-item-title>
                              <v-list-item-subtitle>
                                <span>{{item.updateTime}}</span>
                              </v-list-item-subtitle>
                            </v-list-item-content>
                          </v-list-item>
                        </v-list-item-group>
                      </v-list>
                    </v-col>
<!--                    详细笔记-->
                    <v-col cols="12" lg="9">
                      <v-row no-gutters>
                        <v-col cols="12" lg="11">
                          <mavon-editor
                            class="md"
                            style="height: 50vh"
                            :value="content_note"
                            :subfield="false"
                            :defaultOpen="'preview'"
                            :toolbarsFlag="false"
                            :editable="false"
                            :scrollStyle="true"
                            :ishljs="true"
                            :boxShadow="false"
                          />
                        </v-col>
                        <v-col cols="12" lg="1">
                          <v-btn tile @click="menu = false" width="1px" height="50vh" color="#fffaf4">
                            <span>收<br>起<br>笔<br>记</span>
                            <v-icon>
                              mdi-menu-right
                            </v-icon>
                          </v-btn>
                        </v-col>
                      </v-row>
                    </v-col>
                  </v-row>
                </v-card>
              </v-menu>
            </div>
          </v-col>
        </v-row>
      </div>
    </a-layout-content>
<!--    页面底部固钉-->
    <a-affix :offset-bottom=0 style=" z-index: 100">
      <v-card style="background-color: #FFFAF4" outlined>
        <div style="padding-top: 1vh;padding-bottom: 1vh">
          <v-row justify-lg="center">
<!--            字数统计-->
            <v-col cols="12" lg="2">
              <v-btn text disabled>
                <span style="font-size: 15px; color: grey" v-if="this.TiLength<=20000">
                  共&nbsp;{{TiLength}}/20000&nbsp;字
                </span>
                <span style="font-size: 15px; color: red" v-else>
                  共&nbsp;{{TiLength}}/20000&nbsp;字
                </span>
              </v-btn>
            </v-col>
            <v-col cols="12" lg="1"></v-col>
            <!--            导出按钮-->
            <v-col cols="12" lg="1">
              <v-dialog max-width="400">
                <template v-slot:activator="{ on, attrs }">
                  <v-btn
                    rounded color="grey" outlined
                    v-bind="attrs"
                    v-on="on">
                    导出文件
                    <v-icon right>
                      mdi-file-export
                    </v-icon>
                  </v-btn>
                </template>
                <template v-slot:default="dialog">
                  <v-card class="rounded-xl" elevation="0">
                    <v-card-title>
                      导出解决方案的html文本
                    </v-card-title>
                    <v-card-text style="padding-bottom: 0">确定导出文件吗？</v-card-text>
                    <br><br>
                    <v-card-actions style="padding-top: 0">
                      <v-spacer></v-spacer>
                      <v-btn text @click="dialog.value = false">
                        取消
                      </v-btn>
                      <v-btn text @click="export_draft(dialog)" color="#89B8CA">
                        确认
                      </v-btn>
                    </v-card-actions>
                  </v-card>
                </template>
              </v-dialog>
            </v-col>
<!--            保存草稿按钮-->
            <v-col cols="12" lg="1">
              <v-btn rounded outlined color="grey" @click="save_as_draft" v-if="this.draft.statement==='未发布'">
                保存草稿
                <v-icon right>
                  mdi-content-save
                </v-icon>
              </v-btn>
            </v-col>
<!--            发布解决方案按钮-->
            <v-col cols="12" lg="1">
              <v-dialog max-width="370">
                <template v-slot:activator="{ on, attrs }">
                  <v-btn rounded color="#89B8CA"
                         v-bind="attrs"
                         v-on="on">
                    <span style="color: #FFFAF4">
                      发布解决方案
                    </span>
                    <v-icon right color="#FFFAF4">
                      mdi-upload
                    </v-icon>
                  </v-btn>
                </template>
                <template v-slot:default="dialog">
                  <v-card class="rounded-xl" elevation="0">
                    <v-card-title>
                      发布解决方案
                    </v-card-title>
                    <v-card-text style="padding-bottom: 0">确认发布解决方案吗？</v-card-text>
                    <br><br>
                    <v-card-actions style="padding-top: 0">
                      <v-spacer></v-spacer>
                      <v-btn text @click="dialog.value = false">
                        取消
                      </v-btn>
                      <v-btn text @click="upload_solution(dialog)" color="#89B8CA">
                        确认
                      </v-btn>
                    </v-card-actions>
                  </v-card>
                </template>
              </v-dialog>
            </v-col>
          </v-row>
        </div>
      </v-card>
    </a-affix>
  </a-layout>
</template>

<script>
import GuideStepper from '../components/Stepper'
import GuideRecord from "../components/GuideRecord"
import request from "../utils/request"
// import axios from "axios"


export default {
  name: "solution_edit",
  components: {
    GuideStepper,GuideRecord
  },

  beforeRouterEnter(to, from, next) {
    next((vm) => {
      vm.isShow = true;
    });
  },
  beforeRouterLeave(to, from, next) {
    this.isShow = false;
    next();
  },
  data: () => ({
    isShow: true,
    upload_success: false, //发布成功对话框
    note_list: [], //笔记列表
    note_selected: {}, //当前选中笔记
    selectedItem: null,
    menu: false, //笔记列表显示
    getIn: false, //是否进入详细笔记
    toolbars: { //工具栏选项
      bold: true, // 粗体
      italic: true, // 斜体
      header: true, // 标题
      underline: true, // 下划线
      strikethrough: true, // 中划线
      mark: true, // 标记
      superscript: true, // 上角标
      subscript: true, // 下角标
      quote: true, // 引用
      ol: true, // 有序列表
      ul: true, // 无序列表
      link: true, // 链接
      imagelink: true, // 图片链接
      code: true, // code
      table: true, // 表格
      readmodel: true, // 沉浸式阅读
      htmlcode: true, // 展示html源码
      help: true, // 帮助
      /* 1.3.5 */
      undo: true, // 上一步
      redo: true, // 下一步
      trash: true, // 清空
      save: true, // 保存（触发events中的save事件）
      /* 1.4.2 */
      navigation: true, // 导航目录
      /* 2.1.8 */
      alignleft: true, // 左对齐
      aligncenter: true, // 居中
      alignright: true, // 右对齐
      /* 2.2.1 */
      subfield: true, // 单双栏模式
      preview: true, // 预览
    },
    draft:{
      name: '',
      detail: '',
      statement: '未发布'
    }, //完整解决方案数据
    change_draft: {
      name: '',
      detail: '',
      statement: '未发布'
    }, //完整解决方案数据copy
    urlList: [], //插入图片的URL
    TiLength: 0, //总字数
    content_note: null, //具体笔记显示富文本编辑器内容
    header_rules: [ //标题输入框规则
      value => (value || '').length >= 5 || '不少于5个字',
      value => (value || '').length <= 20 || '不超过20个字'
    ]
  }),
  methods: {
    parseJSONCapture(str) {
      try {return JSON.parse(str);}
      catch (e) {
        this.confirm()
      }
    },
    decodeCapture(str) {
      try {return decodeURIComponent(window.atob(str))}
      catch (e) {
        this.confirm()
      }
    },
    confirm(){
      if (sessionStorage.getItem('guideId'))
        sessionStorage.removeItem('guideId')
      if (sessionStorage.getItem('graph'))
        sessionStorage.removeItem('graph')
      if (sessionStorage.getItem('selectableNodes'))
        sessionStorage.removeItem('selectableNodes')
      this.$router.push('/personal/guide')
    },

    imgAdd(pos, $file) { //上传图片
      let $vm = this.$refs.md
      const formData = new FormData()

      // 压缩图片
      if($file.type.indexOf("image") === 0) {
        let reader = new FileReader(), img = new Image();
        reader.readAsDataURL($file)
        reader.onload = function(e) {
          img.src = e.target.result
        }
        img.onload = function () {
          // 缩放图片需要的canvas（也可以在DOM中直接定义canvas标签，这样就能把压缩完的图片不转base64也能直接显示出来）
          let canvas = document.createElement('canvas');
          let context = canvas.getContext('2d');

          // 图片原始尺寸
          let originWidth = this.width
          let originHeight = this.height

          // 最大尺寸限制，可通过设置宽高来实现图片压缩程度
          let maxWidth = 800, maxHeight = 800
          // 目标尺寸
          let targetWidth = originWidth, targetHeight = originHeight
          // 图片尺寸超过300x300的限制
          if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > maxWidth / maxHeight) {
              // 更宽，按照宽度限定尺寸
              targetWidth = maxWidth;
              targetHeight = Math.round(maxWidth * (originHeight / originWidth));
            } else {
              targetHeight = maxHeight;
              targetWidth = Math.round(maxHeight * (originWidth / originHeight));
            }
          }
          // canvas对图片进行缩放
          canvas.width = targetWidth
          canvas.height = targetHeight
          // 清除画布
          context.clearRect(0, 0, targetWidth, targetHeight)
          // 图片压缩
          context.drawImage(img, 0, 0, targetWidth, targetHeight)
          /*第一个参数是创建的img对象；第二三个参数是左上角坐标，后面两个是画布区域宽高*/

          //压缩后的图片转base64 url
          /*canvas.toDataURL(mimeType, qualityArgument),mimeType 默认值是'image/png';
           * qualityArgument表示导出的图片质量，只有导出为jpeg和webp格式的时候此参数才有效，默认值是0.92*/
          let newUrl = canvas.toDataURL('image/jpeg', 0.8);//base64 格式

          // base64 转 blob 再转 file
          let arr = newUrl.split(","),
            mime = arr[0].match(/:(.*?);/)[1], // 去掉url的头，并转化为byte
            bstr = atob(arr[1]), // 处理异常,将ascii码小于0的转换为大于0
            n = bstr.length,
            u8arr = new Uint8Array(n);
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
          }
          // 转blob
          let filename = Date.parse(new Date()) + ".jpeg"
          // 转file
          let file = new File([u8arr], filename, { type: mime })

          // 将图片上传到服务器
          formData.append('file', file)
          axios({
            url: '/api/file/upload',
            method: 'post',
            data: formData,
            headers: {'Content-Type': 'multipart/form-data'},
          }).then((res) => {
            // 将返回的url替换到文本原位置![...](./0) -> ![...](url)
            $vm.$img2Url(pos, res.data)
          })
        }
      }
    },
    get_detail(item) { //查看笔记具体内容
      this.note_selected = item
      this.content_note = item.content
      this.getIn = !this.getIn
    },
    open_note_list() { //打开笔记列表
      this.menu = !this.menu
      this.content_note = this.note_selected.content
    },
    get_note_list() { //获取笔记列表
      request.get('/guide/isMine', {params: {id: this.parseJSONCapture(this.decodeCapture(sessionStorage.getItem('guideId')))}}).then(res1 => {
        if (res1.code === '200'){
          let guideId = this.parseJSONCapture(this.decodeCapture(sessionStorage.getItem('guideId')))
          request.get("/note/getByUidAndGid",{params: {guideId: guideId,}}).then(res => {
            if(res.data !== null) {
              this.note_list = res.data
              this.note_selected = res.data[0]
            }
          })
        }
        else this.confirm()
      })
    },
    get_draft() { //获取解决方案
      request.get('/guide/isMine', {params: {id: this.parseJSONCapture(this.decodeCapture(sessionStorage.getItem('guideId')))}}).then(res1 => {
        if (res1.code === '200') {
          let guideId = this.parseJSONCapture(this.decodeCapture(sessionStorage.getItem('guideId')))
          request.get("/solution/guide/" + guideId).then(res => {
            if(res.data !== null) {
              if(res.data.statement === '回收') {
                this.$message.warn({ content: '该解决方案在回收站中，后续编辑的内容将无法保存或发布',
                  icon: () =>
                    this.$createElement("a-icon", {
                      props: {
                        type: "frown"
                      }
                    }),
                  top: '100px',
                  duration: 5
                })
              }
              this.draft = JSON.parse(JSON.stringify(res.data))
              this.change_draft = JSON.parse(JSON.stringify(res.data))
            }
          })
        }
        else this.confirm()
      })
    },

    export_draft(dialog) {
      if(this.draft.name.length < 5 || this.draft.name.length > 20) {
        this.sendWarnMessage('标题字数不符合规范,导出失败')
      } else {
        // 导出内容
        let content = this.$refs.md.d_render
        // 文件名
        let title = this.draft.name+'.txt'
        if(content===undefined||content==='') {
          this.sendWarnMessage('暂无导出数据！')
        }else {
          const element = document.createElement('a')
          element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(content))
          element.setAttribute('download', title)
          element.style.display = 'none'
          element.click()
        }
      }
      dialog.value = false
    },



    goto_all_notes() { //跳转到所有笔记页面
      let noteUrl = this.$router.resolve({path: "/personal/note"})
      window.open(noteUrl.href, '_blank')
    },

    save_as_draft() { //保存草稿
      request.get('/guide/isMine', {params: {id: this.parseJSONCapture(this.decodeCapture(sessionStorage.getItem('guideId')))}}).then(res1 => {
        if (res1.code === '200') {
          if(this.draft.name.length < 5 || this.draft.name.length > 20) {
            this.sendWarnMessage('标题字数不符合规范，保存失败')
          } else {
            if(this.TiLength > 20000) {
              this.sendWarnMessage('字数超出限制，保存失败')
            } else {
              if(this.draft.statement === '回收'||this.draft.statement === '已发布'||this.draft.statement === '待审核') {
                this.sendWarnMessage('方案状态不符合，该解决方案可能已被删除或发布')
              } else {
                this.draft.userId = -1
                this.draft.guideId = this.parseJSONCapture(this.decodeCapture(sessionStorage.getItem('guideId')))
                this.draft.statement = '未发布'
                request.post("/solution/save", this.draft).then(res => {
                  if(res.code === '200') {
                    this.sendSuccessMessage('保存成功')
                    this.change_draft.name = this.draft.name
                    this.change_draft.detail = this.draft.detail
                  } else {
                    this.sendWarnMessage('方案状态不符合，该解决方案可能已被删除或发布')
                  }
                })
              }
            }
          }
        }
        else this.confirm()
      })
    },

    interval_save() { //自动保存
      if(this.draft.statement === '已发布' || this.draft.statement === '待审核' || this.draft.statement === '回收') {} else {
        if(this.draft.name.length < 5 || this.draft.name.length > 20 || this.TiLength > 20000) {} else {
          if(this.change_draft.name === this.draft.name&&this.change_draft.detail === this.draft.detail) {} else {
            request.get('/guide/isMine', {params: {id: this.parseJSONCapture(this.decodeCapture(sessionStorage.getItem('guideId')))}}).then(res1 => {
              if (res1.code === '200') {
                this.draft.userId = -1
                this.draft.guideId = this.parseJSONCapture(this.decodeCapture(sessionStorage.getItem('guideId')))
                this.draft.statement = '未发布'
                request.post("/solution/save", this.draft).then(res => {
                  if(res.code === '200') {
                    this.change_draft.name = this.draft.name
                    this.change_draft.detail = this.draft.detail
                    this.sendSuccessMessage('自动保存成功')
                  } else {}
                })
              }
              else this.confirm()
            })
          }
        }
      }
    },

    async upload_solution(dialog) {
      request.get('/guide/isMine', {params: {id: this.parseJSONCapture(this.decodeCapture(sessionStorage.getItem('guideId')))}}).then(res1 => {
        if (res1.code === '200') {
          dialog.value = false
          if(this.draft.name.length < 5 || this.draft.name.length > 20) {
            this.sendWarnMessage('标题字数不符合规范，发布失败')
          } else {
            if(this.TiLength > 20000) {
              this.sendWarnMessage('字数超出限制，发布失败')
            } else {
              if(this.draft.statement === '回收') {
                this.sendWarnMessage('方案状态不符合，该解决方案可能已被删除')
              } else {
                this.draft.statement = '待审核'
                this.draft.userId = -1
                this.draft.guideId = this.parseJSONCapture(this.decodeCapture(sessionStorage.getItem('guideId')))
                request.post("/solution/save", this.draft).then(res => {
                  if(res.code === '200'){
                    this.upload_success = true
                    sessionStorage.removeItem('guideId')
                    sessionStorage.removeItem('graph')
                    sessionStorage.removeItem('selectableNodes')
                    setTimeout(() =>{
                      this.$router.push('/personal/solution')
                    },3000);
                  }
                  else {
                    this.sendWarnMessage('方案状态不符合，该解决方案可能已被删除')
                  }
                })
              }
            }
          }
        }
        else this.confirm()
      })
    },
    onEditorChange(event) { //内容改变事件
      this.TiLength = event.length
    },
  },
  mounted(){
    this.TiLength = this.draft.detail.length
    this.$nextTick(() => {
      setInterval(this.interval_save, 300000)
    })
  },
  created() {
    this.$store.commit('SET_KEEP_ALIVE', ['guidance_questions', 'guidance_model', 'guidance_retrieval', 'solution_edit'])
    this.$store.state.currentStep = 4
    this.get_note_list()
    this.get_draft()
  },
  activated() {
    this.$store.commit('SET_KEEP_ALIVE', ['guidance_questions', 'guidance_model', 'guidance_retrieval', 'solution_edit'])
    this.$store.state.currentStep = 4
    this.get_note_list()
    this.get_draft()
  },

}
</script>

<style>
  .v-dialog{
    box-shadow: none !important;
  }
</style>
